<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2017 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 李邦琦 <1536549251@qq.com>
// +----------------------------------------------------------------------

namespace app\crm\model;
use think\Db;
use think\Model;
use think\Cache;
use think\Loader;

class Customer extends Model
{
    /**
     * 获取部门id下的所有子分类id
     * @param  string $dept_id 部门id
     * @return array           子分类id数组
     */
    public function getDepartment ($dept_id)
    {
        $dept_arr = array();
        $dept = Db::name('sys_department')->where('department_pid', $dept_id)->select();
        foreach ($dept as $val) {
            $dept_arr[] = $val['department_id'];
            $result[] = $this->getDepartment($val['department_id'], $dept_arr);
        }
        foreach ($result as $val) {
            if(is_array($val)) {
                $dept_arr = array_merge($dept_arr, $val);
            }
        }
        return $dept_arr;
    }


    /**
     * 获取客户资料列表
     * @param str $where <查询条件>
     * @param int $page <页码>
     * @param int $limit <每页显示条数>
     * @return array <日报列表信息>
     */
    public function getCustomerData($where,$page,$limit)
    {
        $menuname = "Customer List";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname]; 
        $username = $_SESSION["user_info"]["username"];

        $users = Cache::get('users');
        $member = Cache::get('member');
        // $department = Cache::get('department');
        $count = Db::name('vip_customer_basic')->alias('b')->join('xy_vip_customer_detail d','b.customer_code = d.customer_code')->field('b.*, d.member_level, d.sex, d.age, d.last_order_time, d.last_call_time, d.integral, d.id_card, d.order_num, d.sign_num')->where($where)->count();
        // 查询状态为1的用户数据 并且每页显示10条数据
        $customerList = Db::name('vip_customer_basic')->alias('b')->join('xy_vip_customer_detail d','b.customer_code = d.customer_code')->field('b.*, d.member_level, d.sex, d.age, d.last_order_time, d.last_call_time, d.integral, d.id_card, d.order_num, d.sign_num')->where($where)->limit(($page-1)*$limit,$limit)->order('b.createtime DESC')->select();
        // print_r($customerList);exit;
        foreach ($customerList as &$val) {
            $val['create_name'] = $users[$val['create_user']]['cn_name'];
            $val['old_user'] = $users[$val['old_user']]['cn_name'];
            $val['member_level'] = $member[$val['member_level']]['member_level'];
            $val['distribution'] = empty($val['distribution_time'])?'否':'是';
            switch ($val['sex']) {
                case '1': $val['sex'] = '男'; break;
                case '2': $val['sex'] = '女'; break;
            }
            

            // 签收0次 首单  签收1次 升级  签收2次以上 会员
            switch ($val['customer_type']) {
                case 'first': $val['customer_type'] = '首单客户'; break;
                case 'second': $val['customer_type'] = '升级客户'; break;
                case 'vip': $val['customer_type'] = '会员客户'; break;
            }
            // print_r($_SESSION);exit;
            //判断号码是否加密
            if($priv["encrypt_phone"] == "Y"){
                if($username != "admin"){
                    $val["phone"] = substr($val["phone"],0,3)."*****".substr($val["phone"],-2);
                    $val["telephone"] = substr($val["telephone"],0,3)."*****".substr($val["telephone"],-2);
                }
            }
        }
        $rowsList = count($customerList) ? $customerList : false;
        $arrData["code"] = 0;
        $arrData["msg"] = '';
        $arrData["count"] = $count;
        $arrData["data"] = $rowsList;
        return $arrData;
    }


    /**
     * 获取基本资料和收货地址
     * @param  string $customer_code 获取条件
     * @return json                  地区数据
     */
    public function getAddOrder ($customer_code)
    {
        $result = Db::name('vip_customer_basic')->alias('b')->join('xy_vip_customer_address a','b.customer_code = a.customer_code')->field('b.*,a.*')->where('a.customer_code', $customer_code)->find();
        
        return $result;
    }


    /**
     * 共享客户资料
     * @param  array  $customer_codes   被共享的资料id
     * @param  string $dealuser         被共享到的用户
     * @return json                     执行状态
     */
    public function shareCustomer($customer_codes, $dealuser)
    {
        $data = array(
            'dealuser' => $dealuser,
        );
        foreach ($customer_codes as $v) {
            $customer[] = Db::name('vip_customer_basic')->where('customer_code', $v)->update($data);
        }
        if ($customer) {
            /*$data = array(
                'createtime' => date('Y-m-d H:i:s'),
                'username' => $_SESSION['user_info']['username'],
                'action' => '分享客户 '.$customer_code.' 给 '.$dealuser,
            );
            Loader::model('Log')->insertLog('vip', $data);*/
            echo json_encode(array('success'=>true,'msg'=>'操作成功！'));
        } else {
            echo json_encode(array('msg'=>'操作失败！'));
        }
    }


    /**
     * 新增回访任务
     * @param  array $data 任务内容
     * @return json        创建结果
     */
    public function taskCustomer($data)
    {
        $customer_codes = $data['customer_code'];
        $customer_codes = explode('|', $customer_codes);
        foreach ($customer_codes as $key => $val) {
            $data_task = Db::name('vip_data_customer')->where('customer_code="'.$val.'" AND task_status="N"')->find();
            if ($data_task) {
                $data_task_arr[] = $customer_codes[$key];
                unset($customer_codes[$key]);
            }
        }
        if(empty($customer_codes)) {
            echo json_encode(array('msg'=>'任务创建失败！当前数据已全在任务中。'));
            exit;
        }
        $data_task_str = join(',',$data_task_arr);
        $customer_code = join('","',$customer_codes);
        $customer_code = 'customer_code IN ("'.$customer_code.'")';
        unset($data['customer_code']);
        // 创建任务
        $task_id = Db::name('vip_task')->insertGetId($data);
        if ($task_id) {
            $data = array(
                'task_id' => $task_id,
                'recovery' => 1,
                'create_user' => $data['username'],
                'distribution_time' => date('Y-m-d H:i:s'),
            );
            $result = Db::name('vip_customer_basic')->where($customer_code)->update($data);
            if ($result) {
                if($data_task_str) {
                    echo json_encode(array('success'=>true,'msg'=>"任务创建成功！$data_task_str 等客户已在数据任务中，未加入回访任务。"));
                } else {
                    echo json_encode(array('success'=>true,'msg'=>'任务创建成功！'));
                }
            } else {
                echo json_encode(array('msg'=>'任务创建失败！'));
            }
        } else {
            echo json_encode(array('msg'=>'任务创建失败！'));
        }
        // print_r($task_id);exit;
    }


    /**
     * 分配客户资料
     * @param  array  $customer_codes   被分配的资料id
     * @param  string $create_user      被分配到的用户
     * @return json                     执行状态
     */
    public function transferCustomer($where, $create_user, $transfer_note)
    {
        $users = Cache::get('users');
        // print_r($users);exit;
        $data = array(
            'create_user' => $create_user,
            'transfer_note' => $transfer_note,
            'distribution_time' => date('Y-m-d H:i:s'),
            'task_id' => null,
            'groups' => null,
            'recovery' => 1,
        );

        $result = Db::name('vip_customer_basic')->where($where)->update($data);
        return $result;
    }


    /**
     * 删除客户资料
     * @param  str $customer_code [客户资料id]
     * @return json    [删除状态]
     */
    public function delCustomer($customer_code)
    {
        $result1 = Db::name('vip_customer_basic')->where('customer_code',$customer_code)->delete();
        $result2 = Db::name('vip_customer_detail')->where('customer_code',$customer_code)->delete();
        $result3 = Db::name('vip_customer_address')->where('customer_code',$customer_code)->delete();
        if ($result1 && $result2){
            echo json_encode(array('success'=>true,'msg'=>'删除成功！'));
        } else {
            echo json_encode(array('msg'=>'删除失败！'));
        }
    }


    /**
     * 获取导出数据
     * @param  str $where 导出条件
     * @return array      导出数据
     */
    public function getExportCustomer ($where)
    {
        $field = array(
            'customer_code' => '客户编码',
            'name' => '客户姓名',
            'create_user' => '归属人',
            'import_mark' => '导入标记',
            'customer_type' => '客户类型',
            'member_level' => '会员等级',
            'sex' => '性别',
            'age' => '年龄',
            'integral' => '积分',
            'last_order_time' => '最后开单时间',
            'last_call_time' => '最后回访时间',
            'order_num' => '开单次数',
            'sign_num' => '签收次数',
        );
        // echo $fields_str;exit;
        // 确保字段对应
        $customerList = Db::name('vip_customer_basic')->alias('b')->join('xy_vip_customer_detail d','b.customer_code = d.customer_code')
            ->field('b.customer_code, b.name, b.create_user, b.import_mark, b.customer_type, d.member_level, d.sex, d.age, d.last_order_time, d.last_call_time, d.integral, d.order_num, d.sign_num')
            ->where($where)->order('b.createtime DESC')->select();
        
        $users = Cache::get('users');
        $member = Cache::get('member');

        foreach ($customerList as &$val) {
            $val['create_user'] = $users[$val['create_user']]['cn_name'];
            $val['member_level'] = $member[$val['member_level']]['member_level'];
            switch ($val['sex']) {
                case '1': $val['sex'] = '男'; break;
                case '2': $val['sex'] = '女'; break;
            }

            switch ($val['customer_type']) {
                case 'first': $val['customer_type'] = '首单客户'; break;
                case 'second': $val['customer_type'] = '升级客户'; break;
                case 'vip': $val['customer_type'] = '会员客户'; break;
            }
        }
        $this->exportExcel($customerList, $field, '客户资料');
    }


    /**
     * 导出excel
     * @param  array  $data   数据
     * @param  array  $fields 表头
     * @param  string $name   表名
     */
    public function exportExcel($data, $fields, $name)
    {
        set_time_limit(0);
        ini_set("memory_limit", "1024M"); 
        $path = dirname(__FILE__); //找到当前脚本所在路径
        Loader::import('PHPExcel.Classes.PHPExcel'); //手动引入PHPExcel.php
        Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory'); //引入IOFactory.php 文件里面的PHPExcel_IOFactory这个类
        Loader::import('PHPExcel.Classes.PHPExcel.CachedObjectStorage.PHPTemp'); 

        /*$cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp;
        $cacheSettings = array( 'memoryCacheSize' => '512MB');
        \PHPExcel_Settings::setCacheStorageMethod($cacheMethod,$cacheSettings);*/

        $PHPExcel = new \PHPExcel(); //实例化
        $PHPSheet = $PHPExcel->getActiveSheet();
        $PHPSheet->setTitle("sheet1"); //给当前活动sheet设置名称
        /*以下这段抄的,命名极不规范,有可能是张翼写的*/
        $count = count($fields);
        for($lt=A;$lt<=ZZ;$lt++){
            $yy[] = $lt;
        }
        $letters = array_slice($yy,0,$count);
        //echo json_encode($letters2);exit;
        /*end*/
        // 行数 = $i+1
        for ($i=0; $i < count($data); $i++) { 
            $j = 0;
            foreach ($data[$i] as $k => $v) {
                if ($i == 0) {
                    // print_r($data);exit;
                    $PHPSheet->setCellValue($letters[$j].'1', $fields[$k]); //第一次进来 添加表头
                }
                $PHPSheet->setCellValue($letters[$j].($i+2), $v); //表格数据 第二行开始写入数据
                $j++;
            }
        }

        // $time = microtime(TRUE);
        $PHPWriter = \PHPExcel_IOFactory::createWriter($PHPExcel,"Excel2007"); //创建生成的格式
        // print_r(microtime(true)-$time);exit;
        header('Content-Disposition: attachment;filename="'.$name.'.xls"'); //下载下来的表格名
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $PHPWriter->save("php://output"); //表示在$path路径下面生成demo.xlsx文件
    }


    /**
     * 导入客户资料
     * @return json 导入状态
     */
    public function importExcel()
    {
        set_time_limit(0);
        Loader::import('PHPExcel.Classes.PHPExcel');
        Loader::import('PHPExcel.Classes.PHPExcel.IOFactory.PHPExcel_IOFactory');
        Loader::import('PHPExcel.Classes.PHPExcel.Reader.Excel5');
        //获取表单上传文件
        $file = request()->file('excel');
        $info = $file->validate(['ext' => 'xls'])->move(ROOT_PATH . 'public' . DS . 'uploads');//上传验证后缀名,以及上传之后移动的地址
        if ($info) {
            // echo $info->getFilename();
            $exclePath = $info->getSaveName();  //获取文件名
            $file_name = ROOT_PATH . 'public' . DS . 'uploads' . DS . $exclePath;   //上传文件的地址
            $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
            $obj_PHPExcel =$objReader->load($file_name, $encode = 'utf-8');  //加载文件内容,编码utf-8
            $excel_array=$obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式
            array_shift($excel_array);  //删除第一个数组(标题);
            // echo "<pre>";
            //var_dump($excel_array);exit;
            // excel去重
            $data = [];
            foreach($excel_array as $v) {
                $data[$v[1]] = $v;
            }
            // $result = Db::name('vip_customer_basic')->insertAll($data); //批量插入数据
            $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
            $orderSn = $yCode[intval(date('Y')) - 2017] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
            $i = 10000;
            // 拼接SQL 
            $sql = "TRUNCATE table xy_vip_phone_pool";
            Db::execute($sql); // 清空表
            $sql = "INSERT INTO xy_vip_phone_pool(name, phone, import_address, import_mark, createtime, customer_code) VALUES ";
            foreach ($data as $val) {
                $sql .= '("'.$val[0].'","'.$val[1].'", "'.$val[2].'","'.$_REQUEST['import_mark'].'","'.date('Y-m-d H:i:s').'", "'.($orderSn.$i).'"),';
                $i++;
            }
            $sql = rtrim($sql, ',');
            // echo $sql;exit;
            $result = Db::execute($sql);
            if ($result){
                echo json_encode(array('success'=>true,'msg'=>'导入成功！'));
                $this->mergePhonePool();
            } else {
                echo json_encode(array('msg'=>'导入失败！'));
            }
        } else {
            echo json_encode(array('msg'=>'导入失败！'));
        }
    }


    /**
     * 从导入的表中提取出来, 放入号码池a 去重
     */
    public function mergePhonePool ()
    {
        $phone = Db::name('vip_phone_pool')->select();
        foreach ($phone as $val) {
            $merge = Db::name('vip_phone')->where('phone="'.$val['phone'].'"')->find();
            // 空的插入 有值去重
            if (empty($merge)) {
                Db::name('vip_phone')->insert(array('phone'=>$val['phone']));
                Db::name('vip_phone_pool_a')->insert($val);
            } else {
                continue;
            }
        }
    }


    /**
     * 更新客户基本资料
     * @param  array $data 需要更新的数据
     * @return bool        更新状态 true/false
     */
    public function updateBasicCustomer ($data)
    {
        $result = Db::name('vip_customer_basic')->where('customer_code', $data['customer_code'])->update($data);
        if ($result){
            return true;
        } else {
            return false;
        }
    }


    /**
     * 更新客户基本资料
     * @param  array $data 需要更新的数据
     * @return bool        更新状态 true/false
     */
    public function updateDetailCustomer ($data)
    {
        $result = Db::name('vip_customer_detail')->where('customer_code', $data['customer_code'])->update($data);
        if ($result){
            return true;
        } else {
            return false;
        }
    }


    /**
     * 更新收货地址
     * @param  array $data 需要更新的数据
     * @return bool        更新状态 true/false
     */
    public function updateAddressCustomer ($data)
    {
        // 先查是否存在该客户的收货地址
        // 有 update 无 insert
        $res = Db::name('vip_customer_address')->where('customer_code', $data['customer_code'])->find();
        if ($res) {
            $result = Db::name('vip_customer_address')->where('customer_code', $data['customer_code'])->update($data);
        } else {
            $result = Db::name('vip_customer_address')->where('customer_code', $data['customer_code'])->insert($data);
        }
        // 返回更新结果
        if ($result){
            return true;
        } else {
            return false;
        }
    }


    /**
     * 获取收货地址
     * @param  string $customer_code 获取条件
     * @return json                  地区数据
     */
    public function getAddress ($customer_code)
    {
        $result = Db::name('vip_customer_address')->where('customer_code', $customer_code)->find();
        return $result;
    }


    /**
     * 获取地区
     * @param  string $parent_id 地区父级id
     * @return array             地区数组
     */
    public function getEditAddress ($parent_id) 
    {
        $result = Db::name('sys_address')->where('parent_id='.$parent_id)->select();
        return $result;
    }


    /**
     * 获取病情列表
     * @param  string $where 获取条件
     * @return array         获取到的数据
     */
    public function getIllness ($where)
    {
        $page = $_REQUEST["page"];
        $limit = $_REQUEST["limit"];
        $users = Cache::get('users');
        $count = Db::name('vip_illness')->where($where)->count();
        // 查询状态为1的用户数据 并且每页显示5条数据
        $illnessData = Db::name('vip_illness')->where($where)->limit(($page-1)*$limit,$limit)->order('create_time DESC')->select();
        $illnessSelect = Cache::get('illnessSelect');
        foreach ($illnessData as &$val) {
            $val['create_name'] = $users[$val['create_user']]['cn_name'];
            $val['illness_type'] = $illnessSelect[$val['illness_type']]['illness_type'];
        }
        $rowsList = count($illnessData) ? $illnessData : false;
        $arrData["code"] = 0;
        $arrData["msg"] = '';
        $arrData["count"] = $count;
        $arrData["data"] = $rowsList;
        // print_r($arrData);exit;
        return $arrData;
    }


    /**
     * 获取回访记录列表
     * @param  string $where 获取条件
     * @return array         获取到的数据
     */
    public function getVisit ($where)
    {
        $menuname = "Customere List";
        $p_menuname = $_SESSION['menu'][$menuname]; //父菜单
        $priv = $_SESSION["user_priv"][$p_menuname][$menuname]; 
        $username = $_SESSION["user_info"]["username"];

        $page = $_REQUEST["page"];
        $limit = $_REQUEST["limit"];
        $users = Cache::get('users');
        $visit = Cache::get('visit');
        $count = Db::name('vip_visit_record')->where($where)->count();
        // 查询状态为1的用户数据 并且每页显示5条数据
        $visitData = Db::name('vip_visit_record')->where($where)->limit(($page-1)*$limit,$limit)->order('create_time DESC')->select();
        foreach ($visitData as &$val) {
            $val['create_name'] = $users[$val['create_user']]['cn_name'];
            //判断号码是否加密
            if($priv["encrypt_phone"] == "Y"){
                if($username != "admin"){
                    $val["phone"] = substr($val["phone"],0,3)."*****".substr($val["phone"],-2);
                }
            }
            $val['visit_type_id'] = $visit['visit_type'][$val['visit_type_id']]['visit_type'];
            $val['visit_result_id'] = $visit['visit_result'][$val['visit_result_id']]['result_name'];
            $val['task_id'] = empty($val['task_id'])?'无':$val['task_id'];
        }
        $rowsList = count($visitData) ? $visitData : false;
        $arrData["code"] = 0;
        $arrData["msg"] = '';
        $arrData["count"] = $count;
        $arrData["data"] = $rowsList;
        // print_r($arrData);exit;
        return $arrData;
    }


    /**
     * 新增病情
     * @param  array $data 新增数据
     * @return json        新增状态
     */
    public function insertIllness ($data)
    {
        $result = Db::name('vip_illness')->insert($data);
        return $result;
    }


    /**
     * 获取单条病情
     * @param  string $id 病情id
     * @return array      病情情况
     */
    public function getIllnessInfo($id)
    {
        $where = "id=$id";
        $result = Db::name('vip_illness')->where($where)->find();
        return $result;
    }


    /**
     * 编辑病情
     * @param  array $data 需要更新的数据
     * @return json        更新状态
     */
    public function updateIllness($data)
    {
        $where = "id=".$data['id'];
        $result = Db::name('vip_illness')->where($where)->update($data);
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'编辑成功！'));
        } else {
            echo json_encode(array('msg'=>'编辑失败！'));
        }
    }


    /**
     * 删除病情
     * @param  string $where 删除条件
     * @return json          删除状态
     */
    public function delIllness ($where) 
    {
        if (empty($where)) return false;
        $result = Db::name('vip_illness')->where($where)->delete();
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'删除成功！'));
        } else {
            echo json_encode(array('msg'=>'删除失败！'));
        }
    }


    /**
     * 新增回访记录
     * @param  array $data 新增数据
     * @return json        新增状态
     */
    public function insertVisit ($data)
    {
        // 先根据客户资料id查到客户电话和任务id
        $res = Db::name('vip_customer_basic')->field('phone')->where("customer_code='".$data['customer_code']."'")->find();
        $data['visit_phone'] = $res['phone'];
        // 新增
        $result = Db::name('vip_visit_record')->insert($data);
        if ($result){
            // 添加成功 更新最后回访时间
            $cus = Db::name('vip_customer_detail')->where("customer_code = '".$data['customer_code']."'")->update(['last_call_time' => date("Y-m-d H:i:s")]);
            echo json_encode(array('success'=>true,'msg'=>'保存成功！'));
        } else {
            echo json_encode(array('msg'=>'保存失败！'));
        }
    }


    /**
     * 删除病情
     * @param  string $where 删除条件
     * @return json          删除状态
     */
    public function delVisit ($where) 
    {
        if (empty($where)) return false;
        $result = Db::name('vip_visit_record')->where($where)->delete();
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'删除成功！'));
        } else {
            echo json_encode(array('msg'=>'删除失败！'));
        }
    }


    /**
     * 获取单条回访记录
     * @param  string $id 主键
     * @return array      获取到的数据
     */
    public function getVisitInfo ($id)
    {
        $where = "id=$id";
        $result = Db::name('vip_visit_record')->where($where)->find();
        return $result;
    }


    /**
     * 更新回访记录
     * @param  array $data 更新数据
     * @return json        更新状态
     */
    public function updateVisit($data)
    {
        $where = "id=".$data['id'];
        // print_r($where);exit;
        $result = Db::name('vip_visit_record')->where($where)->update($data);
        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'编辑成功！'));
        } else {
            echo json_encode(array('msg'=>'编辑失败！'));
        }
    }


    /**
     * 回收资料
     * @param  string $where 回收资料条件
     * @return json          回收状态
     */
    public function recovery ($where)
    {
        $customer_recovery = Db::name('vip_customer_basic')->alias('b')->join('xy_vip_customer_detail d','b.customer_code = d.customer_code')->field('b.customer_code, create_user, distribution_time')->where($where)->select();
        // $customer_recovery = Db::name('vip_customer_basic')->field('customer_code, create_user, distribution_time')->where($where)->select();
        foreach ($customer_recovery as $val) {
            $recovery['customer_code'] = $val['customer_code']; // 回收客户资料主键
            $recovery['old_user'] = $val['create_user']; // 回收前归属人
            $recovery['recycle_user'] = $_SESSION['user_info']['username']; // 执行回收人
            $recovery['recycle_time'] = date('Y-m-d H:i:s'); // 回收时间
            $recovery['create_user'] = null; // 创建人
            $recovery['distribution_time'] = null; // 分配时间
            $recovery['groups'] = null; // 分配时间
            $recovery['recovery'] = 2; // 回收状态
            // print_r($recovery);exit;
            $result[] = Db::name('vip_customer_basic')->update($recovery);
        }

        if ($result){
            echo json_encode(array('success'=>true,'msg'=>'回收成功！'));
        } else {
            echo json_encode(array('msg'=>'回收失败！'));
        }
    }


    /**
     * 新增数据任务
     * @param  array $data 新增数据
     * @return json        新增结果
     */
    public function dataTask ($data)
    {
        $result = Db::name('vip_data_task')->insert($data);
        if ($result) {
            echo json_encode(array('success'=>true,'msg'=>'添加成功！'));
        } else {
            echo json_encode(array('msg'=>'添加失败！'));
        }
    }


    /**
     * 新增数据任务客户
     * @param  array $data 新增数据
     * @return json        新增结果
     */
    public function addDataTask ($data)
    {
        // 添加前 该客户资料是否存在任务中
        $res = Db::name('vip_customer_basic')->field('data_task, task_id')->where('customer_code="'.$data['customer_code'].'"')->find();
        if ($res['data_task']) {
            // $result = Db::name('vip_data_customer')->where('customer_code="'.$data['customer_code'].'" AND data_task="'.$data['data_task'].'"')->update($data);
            echo json_encode(array('msg'=>'添加失败，该客户资料已存在数据任务 '.$res['data_task'].' 中！'));
            exit;
        } elseif ($res['task_id']) {
            echo json_encode(array('msg'=>'添加失败，该客户资料已存在回访任务 '.$res['task_id'].' 中！'));
            exit;
        } else {
            $result = Db::name('vip_data_customer')->insert($data);
        }

        if ($result) {
            Db::name('vip_customer_basic')->where('customer_code="'.$data['customer_code'].'"')->update(array('data_task'=>$data['data_task']));
            echo json_encode(array('success'=>true,'msg'=>'添加成功！'));
        } else {
            echo json_encode(array('msg'=>'添加失败！'));
        }
    }


    /**
     * 获取数据任务列表
     * @return array  数据任务表 
     */
    public function getDataTask()
    {
        $result = Db::name('vip_data_task')->field("id,name")->order('createtime DESC')->select();
        return $result;
    }


}